/******************************************************
 * Function: 网络请求同步接口
 *******************************************************/
// const baseUrl = 'https://';

const http = ({ url = '', param = {}, ...other } = {}) => {
  // wx.showLoading({
  //   title: '拼命加载中..'
  // });
  let timeStart = Date.now();
  return new Promise((resolve, reject) => {
    wx.request({
      url: getUrl(url),
      data: param,
      header: {
        // 'content-type': 'application/json' // 默认值 ,另一种是 
        "content-type": "application/x-www-form-urlencoded",
      },
      ...other,
      complete: (res) => {
        // wx.hideLoading();    //要和showLoading配对使用
        // console.log(`网络请求耗时${Date.now() - timeStart}, url:${url}`, res);
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail: (res) => {
        var rs = res.errMsg.substring(8, 12)
        if (rs == "fail") {
          wx.showToast({
            title: '哎呀!服务器跑丢了>_<',
            icon: 'none'
          })
        }  
      }
    })
  })
}

const getUrl = (url) => {
  // if (url.indexOf('://') == -1) {
  //   url = baseUrl + url;
  // }
  return url
}

// get方法
const _get = (url, param = {}) => {
  return http({
    url,
    param
  })
}

const _post = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'POST'
  })
}

const _put = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'PUT'
  })
}

const _delete = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'PUT'
  })
}
/**
 * 对外接口get/post/put/delete
 * @url 请求的url，非空
 * @param 请求数据参数，对象类型，可空
 * @return Promise对象
 */
module.exports = {
  // baseUrl,
  get: _get,
  post: _post,
  put: _put,
  delete: _delete,
}

